﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using RG.Common.Configuration;
using RG.Common.Provider;
using RG.Common.WPF.Frames;
using Microsoft.Practices.Unity;

namespace RG.Common.WPF.Filters
{
    public partial class FilterTemplates
    {
//#if 0  
        #region Команды
        /// <summary>
        /// команда для сохранения настроек презентера(фильтры, колонки и тп)
        /// </summary>
        public static RoutedUICommand CommCheckAllDesc = new RoutedUICommand();
        public static RoutedUICommand CommUnCheckAllDesc = new RoutedUICommand();
        /*
        private CommandBinding[] cmb = {
                                           new CommandBinding(CommCheckAllDesc, ExecuteRoutedEventHandler,
                                                              CanExecuteRoutedEventHandler),
                                           new CommandBinding(CommUnCheckAllDesc, ExecuteRoutedEventHandler,
                                                              CanExecuteRoutedEventHandler),
                                           new CommandBinding(CommInvertAllCheckings, ExecuteRoutedEventHandler,
                                                              CanExecuteRoutedEventHandler)
                                       };*/
                                      
        private   void   CanExecuteRoutedEventHandler(object sender,CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
        private void CanExecuteUnckeckAll(object sender, CanExecuteRoutedEventArgs e)
        {
            var tvVm = GetTVIVMFromContext(sender);
            e.CanExecute =(tvVm!=null  && tvVm.CheckedDescendants!=null &&  tvVm.CheckedDescendants.Count > 0);
        }
        private static TreeViewItemViewModel GetTVIVMFromContext(object sender)
        {
            return (TreeViewItemViewModel)((FrameworkElement)sender).DataContext;
        }
        private void ExecuteUnCheckAllDescendants(object sender, ExecutedRoutedEventArgs e)
        {
            GetTVIVMFromContext(sender).UnCheckAllDescendants();
        }
        private void ExecuteCheckAllDescendants(object sender, ExecutedRoutedEventArgs e)
        {
            //GetTVIVMFromContext(sender).CheckAllDescendants();
        }
        private void ExecuteInverseCheckAllDescendants(object sender, ExecutedRoutedEventArgs e)
        {
            //  GetTVIVMFromContext(sender).InvertCheckingsAllDescendants();
        }
        #endregion
//#endif

        public void OnSelectSubItems(object sender, RoutedEventArgs e)
        {
//            object vm = ((FrameworkElement)sender).DataContext;
//            var tree = (ITree)vm.GetType().GetProperty("Item").GetValue(vm, null);
//            MessageBox.Show(string.Format("Кликнули в ноду [{0}] командой {1}", tree.N_Tree, ((MenuItem)sender).Tag));
        }
    }

    /// <summary>
    /// Фильтр со строковым параметром
    /// </summary>
    [SupportDataBinding]
    public class FrameFilterItemStringVM : FilterBaseVM
    {
        public FrameFilterItemStringVM(IUnityContainer cfg) : base(cfg)
        {
        }

        [PropertySetting]
        public string Value { get; set; }

        public override void ClearValueQuiet()
        {
            Value = "";
        }

        public override bool ValueEmpty()
        {
            return String.IsNullOrEmpty(Value);
        }

        public string FormattedValue
        {
            get
            {
                return ValueEmpty() ? "<не используется>" : Value;
            }
        }
    }

    /// <summary>
    /// Фильтр со строковым параметром
    /// </summary>
    [SupportDataBinding]
    public class FrameFilterItemComboBoxVM : FilterBaseVM
    {
        public FrameFilterItemComboBoxVM(IUnityContainer cfg) : base(cfg)
        {
        }

        [PropertySetting]
        public string Selected { get; set; }

        // Нужен чтобы при ClearValue корректно отрисовывалось
        public int SelectedIndex { get; set; }

        public ObservableCollection<string> DropListItems { get; set; }

        public override void ClearValueQuiet()
        {
            Selected = "";
            SelectedIndex = -1;
        }

        public override bool ValueEmpty()
        {
            return Selected == "";
        }

        public string FormattedValue
        {
            get
            {
                return ValueEmpty() ? "<не используется>" : Selected;
            }
        }
    }

    /// <summary>
    /// Тип фильтра даты
    /// 0 - не используется
    /// 1 - за n последних дней
    /// 2 - интервал дат
    /// </summary>
    public class DateFilterType
    {
        public const int NotUsed = 0;
        public const int LastDays = 1;
        public const int Interval = 2;

        public static readonly DateTime LastKnownDate = new DateTime(2100, 01, 01);
    }

    /// <summary>
    /// Фильтр по дате
    /// </summary>
    [SupportDataBinding]
    public class FrameFilterItemDateVM : FilterBaseVM
    {
        public FrameFilterItemDateVM(IUnityContainer cfg):base(cfg)
        {
            FromDate = DateTime.Now.Date;
            ToDate = DateTime.Now.Date;
        }

        [PropertySetting]
        public int Type { get; set; }

        [PropertySetting]
        public DateTime FromDate { get; set; }

        [PropertySetting]
        public DateTime ToDate { get; set; }

        [PropertySetting]
        public int LastDays { get; set; }

        public string FormattedValue
        {
            get
            {
                switch (Type)
                {
                    case DateFilterType.Interval: return String.Format("с {0:d} по {1:d}", FromDate, ToDate);
                    case DateFilterType.LastDays: return String.Format("За последние {0} дней", LastDays);
                }
                return "Не использовать";
            }
        }

        public override void ClearValueQuiet()
        {
            Type = DateFilterType.NotUsed;
        }

        public override bool ValueEmpty()
        {
            return Type == DateFilterType.NotUsed;
        }

        public DatesRange ToDatesRange()
        {
            var result = new DatesRange();
            if (Type == DateFilterType.LastDays)
            {
                result.minDate = DateTime.Now.AddDays(-LastDays).Date;
                result.maxDate = DateFilterType.LastKnownDate;
            }
            if (Type == DateFilterType.Interval)
            {
                result.minDate = FromDate;
                result.maxDate = ToDate;
            }
            return result;
        }
    }

 
    /// <summary>
    /// Выпадающий список
    /// </summary>
    [SupportDataBinding]
    public class FrameFilterComboBox : FilterBaseVM
    {
        private BindingList<Object> _Items;
      
        public FrameFilterComboBox(IUnityContainer cfg) : base(cfg)
        {

            Items = new BindingList<Object>();
        }

        public override void ClearValue()
        {
           
        }

        public override void ClearValueQuiet()
        {
           
        }

        public override bool ValueEmpty()
        {
            return false;
        }
        public object  SelectedValue { get; set; }

        [PropertySetting]
        public String SelectedItemName { get { return SelectedValue.ToString(); }
            set { if (_Items==null)return ;
            foreach (var c in _Items)
                {
                    if (c.ToString() != value) continue;
                    SelectedValue = c;break;
                }}
        }
        //todo -переделать везде на Observable collection
        public BindingList<Object> Items
        {
            get { return _Items; }
            set
            {
                _Items = value;
                if (value.Count > 0) SelectedValue = value[0];
            }
        }
    }
    
    /// <summary>
    /// Фильтр для назначения фиксированной даты
    /// </summary>
    [SupportDataBinding]
    public class FrameFilterFixedDateVM : FilterBaseVM
    {
        public FrameFilterFixedDateVM(IUnityContainer cfg) : base(cfg)
        {
            FixDate = DateTime.Now.Date;
        }
        
        public DateTime FixDate { get; set; }

        public string FormattedValue
        {
            get
            {
                return String.Format("на {0:d}", FixDate);
            }
        }

        public override void ClearValueQuiet()
        {
            FixDate = DateTime.Now.Date;
        }

        public override bool ValueEmpty()
        {
            return false;
        }
    }
}
